package com.piece.core.web.authority.token;

import com.piece.core.framework.support.dto.UserDetailDTO;
import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;

/**
 * OpenId认证token
 */
@Getter
public class OpenIdAuthenticationToken extends AbstractAuthenticationToken {

    private final String clientId;
    private final String openId;

    public OpenIdAuthenticationToken(String openId, String clientId) {
        super(null);
        super.setAuthenticated(false);

        this.clientId = clientId;
        this.openId = openId;
    }

    public OpenIdAuthenticationToken(String openId, Object detail, Collection<? extends GrantedAuthority> authorities, String clientId) {
        super(authorities);
        super.setDetails(detail);
        super.setAuthenticated(true);

        this.clientId = clientId;
        this.openId = openId;
    }

    @Override
    public Object getPrincipal() {
        Object details = getDetails();
        if (null != details && details instanceof UserDetailDTO) {
            return ((UserDetailDTO) getDetails()).getLoginName();
        }

        return openId;
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) {
        super.setAuthenticated(isAuthenticated);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}
